package com.nowcoder.community.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.Servlet;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * <p>Title: ServiceLogAspect</p>
 * <p>author 12427</p>
 *
 * @version ver1.0
 * @date 2022/8/18 19:42
 */

@Component
@Aspect
public class ServiceLogAspect {
    private  static  final Logger logger = LoggerFactory.getLogger(ServiceLogAspect.class) ;

    @Pointcut("execution(* com.nowcoder.community.service.*.*(..))")
    public void pointcut(){}

    @Before("pointcut()")
    public void before(JoinPoint joinPoint){
        // 用户[1.2.3.4] 在 [xxx] , 访问了 [com.nowcoder.community.service.xxx()]

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes() ;


        // 使用系统通知，是消费者调用Service，不是Controller调用的service ， 找不到attributes
        // 特殊的调用，不去记录日志了
        if(attributes == null){
            return ;
        }

        HttpServletRequest request = attributes.getRequest() ;



        String ip = request.getRemoteHost() ;
        String now = new SimpleDateFormat("yyy-MM-dd HH:mm:ss").format(new Date()) ;
        String target =  joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName() ;
        logger.info(String.format("用户[%s],在[%s],访问了[%s]." , ip , now , target));
    }
}
